Creating, Reading, and Managing Cookies in Java Servlets
Course: Advanced Java Training
Topic: Creating, Reading, and Managing Cookies
Course Link: Advanced Java Training Course
Demo Link: Register for a Course Demo
Website: JustAcademy
1. Introduction to Cookies
Cookies are small pieces of data that a web server asks a browser to store and send back with subsequent requests that match the cookie's rules. In Java web applications, cookies are commonly used to maintain session identifiers, remember user preferences, and support other browser-related features.
HTTP is stateless by default, which means that the protocol does not automatically remember the application state of previous requests. Cookies help applications associate requests with stored information or a session, allowing a web application to provide a more continuous user experience.
In Java Servlets, the jakarta.servlet.http.Cookie class provides methods for creating and configuring cookies. The servlet sends cookies to the browser using HttpServletResponse.addCookie() and reads cookies from incoming requests using HttpServletRequest.getCookies().
Learning Objectives
- Understand cookies and their role in HTTP communication.
- Learn the difference between cookies and HTTP sessions.
- Create cookies using the Java Servlet API.
- Read cookie values from incoming requests.
- Update and delete cookies.
- Configure cookie lifetime, path, and security attributes.
- Understand session cookies and persistent cookies.
- Apply cookie security practices in web applications.
- Build a practical cookie-management application.
2. What Is a Cookie?
A cookie is a small name-value pair stored by the browser. The server can request that the browser save the cookie by sending a Set-Cookie response header. When the browser makes a later request that matches the cookie's domain, path, security, and other applicable rules, it sends the cookie in the Cookie request header.
Example of a Cookie
Set-Cookie: theme=dark; Max-Age=604800; Path=/; Secure; HttpOnly; SameSite=Lax
In this example:
theme is the cookie name.
dark is the cookie value.
Max-Age=604800 requests a lifetime of seven days.
Path=/ makes the cookie available to matching paths throughout the site.
Secure restricts transmission to secure connections.
HttpOnly prevents ordinary client-side JavaScript from reading the cookie.
SameSite=Lax limits some cross-site cookie sending behavior.
This is an illustrative HTTP header. Cookie behavior also depends on browser policies and the application's deployment configuration.
Common Uses of Cookies
| Use Case |
Description |
| Session tracking |
Stores a session identifier used by the server to locate session data. |
| User preferences |
Remembers settings such as theme, language, or display preferences. |
| Shopping carts |
May store a cart identifier that refers to cart data maintained by the server. |
| Personalization |
Helps a site restore selected interface options. |
| Remember-me features |
Can support persistent authentication when implemented with carefully designed security controls. |
| Analytics |
May help measure visits and interactions, subject to applicable privacy requirements. |
3. How Cookies Work in HTTP
Cookie communication generally involves two steps: the server sends a cookie to the browser, and the browser sends the cookie back with later matching requests.
Cookie Request-Response Flow
- The browser sends an HTTP request to a Java web application.
- The servlet creates a cookie or updates an existing cookie.
- The server adds the cookie to the response using
response.addCookie().
- The browser processes the
Set-Cookie header and stores the cookie if permitted.
- The browser sends the cookie with a later request when the cookie's rules allow it.
- The servlet reads the incoming cookies through
request.getCookies().
- The application finds the relevant cookie and uses its value according to the application's logic.
Example HTTP Communication
First request:
GET /preferences HTTP/1.1
Host: example.com
Server response:
HTTP/1.1 200 OK
Set-Cookie: theme=dark; Path=/; Max-Age=604800
Later request:
GET /dashboard HTTP/1.1
Host: example.com
Cookie: theme=dark
The browser controls whether and when cookies are stored and returned. Users can disable or clear cookies, and browser privacy settings may restrict certain cookies.
4. Understanding the Cookie Class in Java
The Cookie class belongs to the jakarta.servlet.http package in modern Jakarta Servlet applications. It represents a cookie that a servlet can send to a browser.
Import Statement
import jakarta.servlet.http.Cookie;
Older Java EE applications may use javax.servlet.http.Cookie. Always use the package that matches your application's Servlet API and server version.
Cookie Constructor
Cookie cookie = new Cookie("username", "Rahul");
The constructor accepts a cookie name and value. Cookie names must comply with cookie syntax rules, and values should be encoded or validated when necessary.
Important Cookie Methods
| Method |
Purpose |
new Cookie(name, value) |
Creates a cookie with a specified name and value. |
cookie.getName() |
Returns the cookie name. |
cookie.getValue() |
Returns the cookie value. |
cookie.setValue(value) |
Changes the value before the cookie is added to a response. |
cookie.setMaxAge(seconds) |
Sets the cookie's requested lifetime in seconds. |
cookie.getMaxAge() |
Returns the configured maximum age. |
cookie.setPath(path) |
Sets the path scope of the cookie. |
cookie.setDomain(domain) |
Sets the domain scope when needed and permitted. |
cookie.setSecure(true) |
Restricts cookie transmission to secure connections. |
cookie.setHttpOnly(true) |
Prevents ordinary client-side scripts from reading the cookie. |
response.addCookie(cookie) |
Adds a cookie to the HTTP response. |
request.getCookies() |
Returns cookies included in the incoming request, or null if none were sent. |
5. Creating Cookies in a Java Servlet
To create a cookie, instantiate the Cookie class, configure its attributes, and add it to the HTTP response.
Example: CreateCookieServlet.java
package com.example.servlet;
import jakarta.servlet.ServletException;
import jakarta.servlet.annotation.WebServlet;
import jakarta.servlet.http.Cookie;
import jakarta.servlet.http.HttpServlet;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import java.io.IOException;
@WebServlet("/create-cookie")
public class CreateCookieServlet extends HttpServlet {
@Override
protected void doGet(HttpServletRequest request,
HttpServletResponse response)
throws ServletException, IOException {
Cookie cookie = new Cookie("theme", "dark");
cookie.setMaxAge(7 * 24 * 60 * 60);
cookie.setPath(request.getContextPath().isEmpty()
? "/" : request.getContextPath());
cookie.setHttpOnly(true);
cookie.setSecure(request.isSecure());
response.addCookie(cookie);
response.setContentType("text/plain;charset=UTF-8");
response.getWriter().println(
"Theme preference cookie has been added to the response."
);
}
}
Explanation
new Cookie("theme", "dark") creates a cookie named theme with the value dark.
setMaxAge() requests a lifetime of seven days.
setPath() scopes the cookie to the application's context path, or the whole site when the application runs at the root.
setHttpOnly(true) prevents ordinary client-side JavaScript from accessing the cookie.
setSecure(request.isSecure()) sets the Secure flag when the request is recognized as secure.
response.addCookie(cookie) adds the cookie to the response.
Deployment note: In production, configure Secure cookies according to the actual HTTPS deployment. If TLS terminates at a reverse proxy, verify the server's trusted proxy configuration instead of relying blindly on the incoming request's security flag.
6. Reading Cookies from an HTTP Request
When a browser sends cookies to the server, a servlet can retrieve them using request.getCookies(). This method returns an array of Cookie objects, or null when the request contains no cookies.
Example: ReadCookieServlet.java
package com.example.servlet;
import jakarta.servlet.ServletException;
import jakarta.servlet.annotation.WebServlet;
import jakarta.servlet.http.Cookie;
import jakarta.servlet.http.HttpServlet;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import java.io.IOException;
@WebServlet("/read-cookie")
public class ReadCookieServlet extends HttpServlet {
@Override
protected void doGet(HttpServletRequest request,
HttpServletResponse response)
throws ServletException, IOException {
String theme = null;
Cookie[] cookies = request.getCookies();
if (cookies != null) {
for (Cookie cookie : cookies) {
if ("theme".equals(cookie.getName())) {
theme = cookie.getValue();
break;
}
}
}
response.setContentType("text/plain;charset=UTF-8");
if (theme != null) {
response.getWriter().println(
"Saved theme preference: " + theme
);
} else {
response.getWriter().println(
"No theme preference cookie was found."
);
}
}
}
How the Code Works
- The servlet calls
request.getCookies().
- It checks whether the returned array is
null.
- A loop examines each cookie's name.
- When the name matches
theme, the servlet retrieves the value.
- The response displays the preference or a message when the cookie is unavailable.
Cookie values are supplied by the client and should not be trusted as proof of identity, authorization, or permission. Validate values before using them, and never treat a user-controlled preference cookie as an authentication credential.
7. Updating an Existing Cookie
To update a cookie, create a cookie with the same name and compatible path and domain scope, set the new value, and add it to the response. The browser processes the new Set-Cookie instruction and replaces the matching cookie.
Example: Update a Theme Cookie
Cookie cookie = new Cookie("theme", "light");
cookie.setPath(
request.getContextPath().isEmpty()
? "/"
: request.getContextPath()
);
cookie.setMaxAge(7 * 24 * 60 * 60);
cookie.setHttpOnly(true);
cookie.setSecure(request.isSecure());
response.addCookie(cookie);
This code requests that the browser store light as the theme value. To update an existing cookie successfully, match the cookie's name and the relevant path and domain scope. Cookies with the same name but different paths or domains may coexist.
Example: Preference Update Servlet
@WebServlet("/update-theme")
public class UpdateThemeServlet extends HttpServlet {
@Override
protected void doPost(HttpServletRequest request,
HttpServletResponse response)
throws ServletException, IOException {
String theme = request.getParameter("theme");
if (!"light".equals(theme) && !"dark".equals(theme)) {
response.sendError(
HttpServletResponse.SC_BAD_REQUEST,
"Invalid theme preference."
);
return;
}
String path = request.getContextPath().isEmpty()
? "/" : request.getContextPath();
Cookie cookie = new Cookie("theme", theme);
cookie.setPath(path);
cookie.setMaxAge(7 * 24 * 60 * 60);
cookie.setHttpOnly(true);
cookie.setSecure(request.isSecure());
response.addCookie(cookie);
response.sendRedirect(
request.getContextPath() + "/read-cookie"
);
}
}
For a real application, protect state-changing endpoints against CSRF when appropriate, especially when the browser automatically includes authentication cookies.
8. Deleting a Cookie
To request deletion of a cookie, send another cookie with the same name and matching path and domain scope, but set its maximum age to zero. The browser then removes the matching cookie if the scope matches.
Example: DeleteCookieServlet.java
package com.example.servlet;
import jakarta.servlet.ServletException;
import jakarta.servlet.annotation.WebServlet;
import jakarta.servlet.http.Cookie;
import jakarta.servlet.http.HttpServlet;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import java.io.IOException;
@WebServlet("/delete-cookie")
public class DeleteCookieServlet extends HttpServlet {
@Override
protected void doPost(HttpServletRequest request,
HttpServletResponse response)
throws ServletException, IOException {
String path = request.getContextPath().isEmpty()
? "/" : request.getContextPath();
Cookie cookie = new Cookie("theme", "");
cookie.setPath(path);
cookie.setMaxAge(0);
cookie.setHttpOnly(true);
cookie.setSecure(request.isSecure());
response.addCookie(cookie);
response.setContentType("text/plain;charset=UTF-8");
response.getWriter().println(
"A request to delete the theme cookie has been sent."
);
}
}
Important Points About Cookie Deletion
- Use the same cookie name.
- Match the original path and domain scope.
- Set the maximum age to zero.
- The deletion response must reach the browser for the browser to process it.
- Deleting a cookie does not automatically invalidate a server-side HTTP session.
If a cookie was created with a custom path or domain, a deletion instruction using a different scope may leave the original cookie unchanged.
9. Session Cookies and Persistent Cookies
Cookies can be classified according to their requested lifetime.
Session Cookies
A session cookie generally has no persistent expiration time. Browsers usually retain it for the current browsing session, but browser session-restoration features may preserve it longer than expected.
Cookie cookie = new Cookie("displayMode", "compact");
cookie.setPath("/");
cookie.setMaxAge(-1);
response.addCookie(cookie);
A negative maximum age indicates that the cookie is not requested to be stored persistently.
Persistent Cookies
A persistent cookie has a positive maximum age and may remain stored until its expiration time, subject to browser policies and user actions.
Cookie cookie = new Cookie("language", "en");
cookie.setPath("/");
cookie.setMaxAge(30 * 24 * 60 * 60);
response.addCookie(cookie);
This example requests a lifetime of 30 days.
Comparison Table
| Feature |
Session Cookie |
Persistent Cookie |
| Lifetime |
Usually associated with the browser session. |
Has a configured expiration time. |
| Typical configuration |
Negative maximum age. |
Positive maximum age. |
| Common use |
Temporary preferences or session tracking. |
Language or theme preferences. |
| Browser behavior |
May survive browser restarts when session restoration is used. |
May be removed before expiration by the user or browser. |
10. Cookie Attributes and Their Importance
Cookie attributes define when a cookie is stored, when it is sent, and how it can be accessed. Correct attribute selection improves compatibility and security.
| Attribute |
Description |
Example |
| Max-Age |
Requests a cookie lifetime in seconds. |
cookie.setMaxAge(3600) |
| Path |
Controls which request paths receive the cookie. |
cookie.setPath("/app") |
| Domain |
Controls which domain may receive the cookie. |
cookie.setDomain("example.com") |
| Secure |
Restricts sending the cookie to secure connections. |
cookie.setSecure(true) |
| HttpOnly |
Prevents ordinary JavaScript access to the cookie. |
cookie.setHttpOnly(true) |
| SameSite |
Controls cookie sending in cross-site request contexts. |
SameSite=Lax |
Understanding the Path Attribute
The path determines which URL paths are eligible to receive the cookie. A cookie scoped to /portal is generally sent to matching paths under that path, but not to unrelated paths such as /shop.
Understanding the Domain Attribute
If the domain attribute is omitted, the browser generally treats the cookie as host-only. Setting a broader domain can make a cookie available to additional subdomains, which should be done only when necessary.
Understanding the Secure Attribute
Cookies with the Secure attribute are sent only over secure connections. Use HTTPS for production applications and configure the cookie accordingly.
Understanding the HttpOnly Attribute
The HttpOnly attribute prevents ordinary client-side JavaScript from reading the cookie. It is useful for sensitive cookies such as session identifiers, although it does not prevent every form of cross-site scripting or cookie misuse.
Understanding the SameSite Attribute
The SameSite attribute influences whether a browser sends a cookie in cross-site contexts. Common values include Strict, Lax, and None. When None is used, modern browsers generally require the Secure attribute as well.
11. Configuring SameSite in Java Servlets
Support for setting cookie attributes varies by Servlet API version. In recent Servlet APIs, the Cookie class provides a general attribute-setting method. For example, with an API version that supports setAttribute(), a cookie can be configured as follows.
Cookie cookie = new Cookie("preference", "dark");
cookie.setPath("/");
cookie.setHttpOnly(true);
cookie.setSecure(true);
cookie.setMaxAge(7 * 24 * 60 * 60);
cookie.setAttribute("SameSite", "Lax");
response.addCookie(cookie);
Verify that your target Servlet API and container support the relevant method. For older APIs, configure SameSite using a supported server or framework configuration rather than manually concatenating untrusted values into a Set-Cookie header.
For session cookies, review the servlet container's session-cookie configuration as well. Configuring an ordinary application cookie does not automatically configure the container-managed session cookie.
12. Cookies vs. HTTP Sessions
Cookies and HTTP sessions are related but different mechanisms. A cookie is stored by the browser, whereas an HTTP session is an application mechanism for maintaining state across requests.
| Feature |
Cookies |
HTTP Sessions |
| Typical storage |
Browser |
Usually server-side, or in a session store |
| API |
Cookie |
HttpSession |
| Data sent on requests |
Matching cookie values are sent by the browser. |
Session data is usually retrieved by the server using a session identifier. |
| Lifetime |
Controlled by cookie attributes and browser behavior. |
Controlled by session lifecycle and timeout settings. |
| Size |
Small; browsers enforce practical limits. |
Can hold multiple server-side attributes, but should remain reasonably small. |
| Security concern |
Client can inspect or alter non-protected values. |
Session identifiers must be protected from theft or misuse. |
| Example |
Remembering a theme preference. |
Maintaining server-side login state. |
A common session-based application stores the session data on the server and uses a cookie to carry the session identifier. This does not mean that the cookie itself contains the entire session.
13. Practical Example: Remembering a User's Theme
This example demonstrates how cookies can preserve a user's preferred display theme between visits. It uses an allowlist to validate the preference before saving it.
Step 1: Create a Theme Selection Form
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Theme Preference</title>
</head>
<body>
<h2>Choose Your Theme</h2>
<form action="save-theme" method="post">
<label for="theme">Theme:</label>
<select name="theme" id="theme">
<option value="light">Light</option>
<option value="dark">Dark</option>
</select>
<button type="submit">Save Preference</button>
</form>
<p><a href="show-theme">View Saved Theme</a></p>
</body>
</html>
Step 2: Save the Theme Cookie
@WebServlet("/save-theme")
public class SaveThemeServlet extends HttpServlet {
@Override
protected void doPost(HttpServletRequest request,
HttpServletResponse response)
throws ServletException, IOException {
String theme = request.getParameter("theme");
if (!"light".equals(theme) && !"dark".equals(theme)) {
response.sendError(
HttpServletResponse.SC_BAD_REQUEST,
"Invalid theme."
);
return;
}
String path = request.getContextPath().isEmpty()
? "/" : request.getContextPath();
Cookie cookie = new Cookie("theme", theme);
cookie.setPath(path);
cookie.setMaxAge(30 * 24 * 60 * 60);
cookie.setHttpOnly(true);
cookie.setSecure(request.isSecure());
response.addCookie(cookie);
response.sendRedirect(
request.getContextPath() + "/show-theme"
);
}
}
Step 3: Read and Display the Theme
@WebServlet("/show-theme")
public class ShowThemeServlet extends HttpServlet {
@Override
protected void doGet(HttpServletRequest request,
HttpServletResponse response)
throws ServletException, IOException {
String theme = "light";
Cookie[] cookies = request.getCookies();
if (cookies != null) {
for (Cookie cookie : cookies) {
if ("theme".equals(cookie.getName())) {
String value = cookie.getValue();
if ("light".equals(value)
|| "dark".equals(value)) {
theme = value;
}
break;
}
}
}
response.setContentType("text/html;charset=UTF-8");
response.getWriter().println(
"<h2>Your saved theme is: "
+ theme
+ "</h2>"
);
}
}
Expected Output
- If the user selects dark, the browser receives a cookie containing the value
dark.
- When the user opens the display page, the servlet reads the cookie.
- If the cookie contains an allowed value, the application displays the saved theme.
- If no valid cookie is available, the application uses the default theme.
14. Cookie Security Best Practices
Cookies are controlled by the browser and can be exposed to risks if they are configured or used incorrectly. Security is especially important when cookies are used for authentication or session tracking.
Recommended Practices
- Use HTTPS: Encrypt communication between the browser and server.
- Set Secure: Restrict sensitive cookies to secure connections in production.
- Set HttpOnly: Prevent ordinary JavaScript from reading session identifiers and other sensitive cookies.
- Choose an appropriate SameSite policy: Reduce unwanted cross-site cookie transmission, while ensuring required workflows still work.
- Do not store passwords: Never store raw passwords or other secrets in ordinary cookies.
- Do not trust cookie values: Validate all values received from the browser.
- Keep cookies small: Store only what is needed, and use server-side storage for larger data.
- Limit cookie scope: Set an appropriate path and avoid broad domain settings unless required.
- Use short lifetimes for sensitive cookies: Reduce the time window in which a stolen cookie may be misused.
- Protect state-changing operations: Use CSRF protection where appropriate; SameSite is helpful but is not a complete replacement for a CSRF defense.
- Invalidate sessions on logout: Removing a preference cookie is not the same as invalidating a server-side authenticated session.
- Apply privacy requirements: Obtain consent where required and disclose relevant cookie usage.
Why Sensitive Data Should Not Be Stored Directly in Cookies
Cookie values are sent to the browser and may be visible to the user or modifiable by the client. Base64 encoding does not provide encryption, and signing a value does not make it confidential. For authentication, prefer a properly designed session identifier or a secure token implementation rather than storing credentials in a cookie.
15. Common Cookie Errors and Troubleshooting
| Problem |
Possible Cause |
Solution |
| Cookie is not returned |
Wrong path, domain, Secure setting, or browser policy |
Inspect the cookie attributes and browser developer tools. |
request.getCookies() returns null |
No cookies were sent with the request |
Check whether the cookie was created and whether its scope matches the request. |
| Cookie does not update |
Name, path, or domain does not match the original cookie |
Use the same relevant cookie scope. |
| Cookie is not deleted |
Deletion cookie uses a different path or domain |
Send a zero-age cookie with matching scope. |
| Cookie is unavailable over HTTP |
Secure attribute is enabled |
Use HTTPS for secure cookies in the intended environment. |
| JavaScript cannot read a cookie |
HttpOnly attribute is enabled |
This is expected; access it through an appropriate server-side mechanism. |
| Cookie value contains unexpected data |
Client changed or supplied the value |
Validate and allowlist values before use. |
| Multiple cookies share a name |
Different path or domain scopes |
Review the cookie scope and remove obsolete cookies with the correct scope. |
| Cookie does not persist after browser closure |
It is a session cookie or browser policy removed it |
Set a suitable positive maximum age when persistence is required. |
16. Practical Exercise: Build a Cookie Management Application
Create a small Java web application that allows users to save, read, update, and delete a language preference using cookies.
Project Requirements
- Create an HTML form with language options such as English, Hindi, and Marathi.
- Create a servlet that validates the selected language.
- Create a cookie named
language with the selected value.
- Set an appropriate cookie path and lifetime.
- Read the cookie on a separate servlet and display the selected language.
- Allow the user to update the language preference.
- Add a POST endpoint that requests deletion of the cookie.
- Handle cases where cookies are disabled or missing.
- Test the application using browser developer tools.
- Verify that cookies use the intended attributes in the target environment.
Expected Result
The application should store a valid language preference, retrieve it on a later request, allow updates, and request deletion when the user resets the preference. It should use a default language when no valid cookie is available.
Additional Challenges
- Store a light or dark theme preference.
- Configure Secure, HttpOnly, and SameSite attributes.
- Compare cookie-based preferences with session-based preferences.
- Test the application with browser cookies disabled.
- Document how cookie lifetime and scope affect browser behavior.
17. Interview Questions and Answers
Q1. What is a cookie in Java web development?
Answer: A cookie is a small name-value pair stored by the browser and sent back to a server with later matching requests. It can support preferences, session tracking, and other web application features.
Q2. Which class is used to create cookies in Java Servlets?
Answer: The jakarta.servlet.http.Cookie class is used in modern Jakarta Servlet applications. Older applications may use javax.servlet.http.Cookie.
Q3. How do you create a cookie?
Answer: Create an instance using new Cookie("name", "value"), configure its attributes, and send it through response.addCookie(cookie).
Q4. How do you read cookies in a servlet?
Answer: Call request.getCookies(), check whether the result is null, and loop through the array to find the cookie by name.
Q5. What does setMaxAge() do?
Answer: It sets the cookie's requested maximum lifetime in seconds. A positive value requests persistence, zero requests deletion, and a negative value indicates a non-persistent cookie.
Q6. How do you update a cookie?
Answer: Send a cookie with the same name and matching path and domain scope, but with the new value and desired attributes.
Q7. How do you delete a cookie?
Answer: Send a cookie with the same name and matching path and domain scope, setting its maximum age to zero.
Q8. What is the difference between a session cookie and a persistent cookie?
Answer: A session cookie generally has no persistent expiration time, whereas a persistent cookie has a configured lifetime and may remain stored beyond the current browsing session.
Q9. What is the purpose of HttpOnly?
Answer: The HttpOnly attribute prevents ordinary client-side JavaScript from reading a cookie, helping reduce exposure of sensitive cookies to some script-based attacks.
Q10. What is the purpose of the Secure attribute?
Answer: It restricts a cookie to secure connections, normally HTTPS.
Q11. What is SameSite?
Answer: SameSite is a cookie attribute that controls when a browser sends the cookie in cross-site request contexts. It can help reduce certain CSRF risks.
Q12. What is the difference between a cookie and an HTTP session?
Answer: A cookie is browser-stored data, while an HTTP session is a server-managed mechanism for maintaining state. A cookie often contains the identifier used to locate a server-side session.
Q13. Can a user modify a cookie?
Answer: Yes. Client-side cookie values can be changed by the user or browser tools. Applications must validate cookie values and should not trust them as proof of authorization.
Q14. Should passwords be stored in cookies?
Answer: No. Raw passwords should never be stored in cookies. Authentication should use an appropriately designed session or secure token mechanism.
18. Quick Revision Checklist
- A cookie is a small piece of browser-stored data.
- The server sends cookies through the
Set-Cookie response header.
- The browser returns eligible cookies in the
Cookie request header.
- Use
new Cookie(name, value) to create a cookie.
- Use
response.addCookie() to add a cookie to the response.
- Use
request.getCookies() to retrieve cookies sent by the browser.
- Use
setMaxAge() to configure the requested lifetime.
- Match the original path and domain when updating or deleting a cookie.
- Use Secure, HttpOnly, and SameSite attributes appropriately.
- Do not store passwords or unnecessary sensitive information in cookies.
- Validate cookie values because the client can modify them.
- Remember that deleting a cookie does not automatically invalidate an HTTP session.
19. Conclusion
Creating, reading, and managing cookies is an essential skill in Advanced Java web development. Cookies allow a browser to retain small pieces of information and return them to the server during later matching requests.
In Java Servlets, the Cookie class is used to create and configure cookies, HttpServletResponse.addCookie() sends them to the browser, and HttpServletRequest.getCookies() retrieves cookies from incoming requests. Developers can update and delete cookies by sending new cookie instructions with matching scope.
Effective cookie management requires understanding expiration, path, domain, Secure, HttpOnly, and SameSite attributes. By combining these concepts with HTTPS, input validation, session security, and appropriate privacy controls, developers can build more reliable and secure web applications.
Continue Learning with JustAcademy
Explore enterprise Java development topics through the Advanced Java Training Course.
Interested in learning through a demo? Visit Register for a Course Demo.
Visit the JustAcademy website to explore additional training programs.